<template>
  <div class="homepage">
    <div class="header" v-if="haveVideo == 1">
      <video-player
        class="video-player vjs-custom-skin"
        ref="videoPlayer"
        :playsinline="true"
        :options="playerOptions"
      ></video-player>
    </div>
    <!-- <button @click="goBack()">回到底部</button> -->
    <div class="brief">
      <p>{{ name }}</p>
      <p>
        {{ basicInfo }}
      </p>
    </div>
    <div class="price" v-show="isAdFlag">
      <span>课程金额</span>
      <span class="number">￥{{ price }}</span>
    </div>
    <div class="course">课程详情</div>
    <div class="conent" v-html="content">
      {{ content }}
    </div>
    <div class="apply" v-show="isAdFlag">
      <button class="apply_btn" @click="applay" v-show="buyStatus == 0">
        立即报名
      </button>
      <button
        class="apply_btn"
        style="background:#ccc;"
        v-show="buyStatus == 1"
      >
        已报名
      </button>
    </div>
    <!-- <div v-if="btnFlag" class="btn">
      <button @click="goscrllo()">置顶</button>
    </div> -->
  </div>
</template>
<script>
import { wxLogintwo, codeData1, Sdksig, getCourseNop } from "../../api/api";
import querystring from "query-string";
import axios from "axios";
import { Indicator, Toast } from "mint-ui";

export default {
  name: "Apphomepage",
  data() {
    return {
      isAdFlag:true,
      pwd: "",
      nowtime: "",
      url: "",
      signature: "",
      queryList: "",
      content: "",
      price: "",
      basicInfo: "",
      haveVideo: "",
      name: "",
      branchId: "",
      buyStatus: 0,
      btnFlag: true,
      playerOptions: {
        playbackRates: false, //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", //这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: "" //url地址
          }
        ],
        poster: "../../../static/image/cover.png", //你的封面地址
        //width:document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true //全屏按钮
        }
      }
    };
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player;
    }
  },
  created() {
    // let href = window.location.href;
    // console.log(href);
    // if (href.includes("/?code")) {
    //   let sp1 = href.split("/?code=");
    //   let code = sp1[1].split("&")[0];
    //   console.log(code);
       
    //   this.getDa(code);
    // }
    // if (localStorage.getItem("token")) {
    //   console.log("已登录");
    // } else {
    //   if (this.$route.query.code == null || this.$route.query.code == "" ) {
    //     if (sessionStorage.getItem("isflag")=="1") {
    //       this.$router.push({ 
    //         path: '/applicationform/four'
    //       })
    //     }else{
    //        console.log(this.$route.query);
    //       this.wxLoginBtn();
    //     }
    //   } else {
    //     let code = this.$route.query.code;
    //     localStorage.setItem("code", code);
    //   }
    // }
  },
  mounted() {
    // this.wxInit();
    this.getCourse();
    let User = JSON.parse(localStorage.getItem("user"));
    // if(this.$route.query.branchId == '' || this.$route.query.branchId == null){
    //   this.branchId = User.branchId;
    // }else{
    //   this.branchId = this.$route.query.branchId
    // }
    let courseId=this.$route.query.courseId;
    localStorage.setItem('courseId',courseId)
    window.addEventListener("scroll", this.scrollToTop);
    window.addEventListener("scroll", this.scrollBottom);
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop);
    window.removeEventListener("scroll", this.scrollBottom);
  },
  methods: {
    // wxLoginBtn() {
    //   let appid = "wxc74ae6a677c8b11d";
    //   if(this.$route.query.branchId == '' || this.$route.query.branchId == null){
    //     var redirect_uri = encodeURIComponent(
    //     `https://xcy.shuidongjia.net/#/applicationform/homepage?courseId=${this.$route.query.courseId}`
    //   );
    //   }else{
    //     var redirect_uri = encodeURIComponent(
    //     `https://xcy.shuidongjia.net/#/applicationform/homepage?courseId=${this.$route.query.courseId}&branchId=${this.$route.query.branchId}`
    //   );
    //   }
    //   console.log(redirect_uri)
    //   window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect`;
    // },
    // getDa(codeVavl) {
    //   console.log(codeVavl);
    //   localStorage.setItem("code", codeVavl);
    //   let params = {
    //     code: codeVavl
    //   };
    //   params = querystring.stringify(params);
    //   let a = localStorage.getItem("token");
    //   a = JSON.parse(a);
    //   codeData1(params, a).then(res => {
    //     console.log(res.data);
    //     if (res.data.code == 1) {
    //       localStorage.setItem("token", JSON.stringify(res.data.data.token));
    //       let userList = res.data.data.user;
    //       localStorage.setItem("user", JSON.stringify(userList));
          
    //     } else if (res.data.code == 5006) {
    //         sessionStorage.setItem("isflag", "1");
    //     }else{
    //       Toast(res.data.message);
    //     }
    //   });
    // },
    //置顶
    // goscrllo() {
    //   let that = this;
    //   let timer = setInterval(() => {
    //     let ispeed = Math.floor(-that.scrollTop / 5);
    //     document.documentElement.scrollTop = document.body.scrollTop =
    //       that.scrollTop + ispeed;
    //     if (that.scrollTop === 0) {
    //       clearInterval(timer);
    //     }
    //   }, 16);
    // },
    //回到底部
    // goBack() {
    //   const that = this;
    // },
    //为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop > 60) {
        that.btnFlag = true;
      } else {
        that.btnFlag = false;
      }
    },
    scrollBottom(){
      
    },
    getTime() {
      this.nowtime = Math.round(new Date().getTime() / 1000).toString();
    },
    randomString(len) {
      len = len || 32;
      var $chars =
        "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length;
      var pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      this.pwd = pwd;
    },
    //微信分享
    wxInit() {
      let that = this;
      let newUser = JSON.parse(localStorage.getItem("user"));
      let branchId = newUser.branchId;
      console.log(branchId);
      let roleCode = newUser.roleCode;
      if (branchId == null) {
        branchId = 0;
      }
      var stateObject = {};
      let url = window.location.href.split("#")[0];
      let links = `${url}#/applicationform/homepage?courseId=${that.$route.query.courseId}&branchId=${branchId}`;
        console.log(links);
     if (location.toString().indexOf("?") == "-1") {
        links = window.location.href;
      } else {
      }
      window.history.pushState(stateObject, links);
      let params = {
        noncestr: that.pwd,
        timestamp: that.nowtime,
        url: links
      };
      params = querystring.stringify(params);
      Sdksig(params).then(res => {
        that.signature = res.data.data.signature;
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: "wxc74ae6a677c8b11d", // 必填，公众号的唯一标识
          timestamp: that.nowtime, // 必填，生成签名的时间戳
          nonceStr: that.pwd, // 必填，生成签名的随机串
          signature: that.signature, // 必填，签名
          jsApiList: [
            "onMenuShareTimeline", // 分享到朋友圈
            "onMenuShareAppMessage", // 分享到微信好友
            "onMenuShareQQ", // 分享到QQ
            "onMenuShareWeibo", // 分享到微博
            "onMenuShareQZone", // 分享到空间
            "hideMenuItems", // 批量隐藏菜单
            "scanQRCode",
            "translateVoice",
            "updateTimelineShareData"
          ]
        });
        //微信分享
        wx.ready(function() {
          //分享到朋友圈
          wx.onMenuShareTimeline({
            title: that.name, // 分享时的标题
            link: links, // 分享时的链接
            imgUrl: that.imgUrl, // 分享时的图标
            success: function() {
              Toast("分享成功");
            },
            cancel: function() {
              Toast("取消分享");
            }
          });
          wx.onMenuShareAppMessage({
            title: that.name, // 分享时的标题
            link: links, // 分享时的链接
            imgUrl: that.imgUrl, // 分享时的图标
            success: function() {
              Toast("分享成功");
            },
            cancel: function() {
              Toast("取消分享");
            }
          });
        });
      });
    },
    //调取课程
    getCourse() {
      Indicator.open("加载中...");
      var params = {
        courseId: this.$route.query.courseId
        // courseId: 5
      };
      var params = querystring.stringify(params);
      var a = localStorage.getItem("token");
      a = JSON.parse(a);
      getCourseNop(params, a).then(res => {
        if (res.data.code == 1) {
          var list = this.playerOptions.sources;
          for (var i = 0; i < list.length; i++) {
            list[i].src = res.data.data.videoUrl;
          }
          this.isAd = res.data.data.isAd;
          if(this.isAd == 1){
            this.isAdFlag = true;
          }else if(this.isAd == 2){
             this.isAdFlag = false;
          }
          this.playerOptions.sources = list;
          this.name = res.data.data.name;
          this.content = res.data.data.content;
          this.price = res.data.data.price;
          this.basicInfo = res.data.data.basicInfo;
          this.haveVideo = res.data.data.haveVideo;
          this.buyStatus = res.data.data.buyStatus;
          console.log(this.buyStatus);
          Indicator.close();
        } else {
          Indicator.close();
          Toast(res.data.message);
        }
      });
    },
    //立即报名
    applay() {
      this.$router.push({
        path: "/applicationform/login",
        query: {
          price: this.price,
          courseId: this.$route.query.courseId,
          branchId: this.branchId
        }
      });
    }
  }
};
</script>
<style lang="scss">
.conent {
  img {
    width: 93%;
    height: 93%;
    margin: auto;
  }
}
</style>
<style scoped lang="scss">
.homepage {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.homepage .header {
  width: 93%;
  height: auto;
  margin-top: 0.3rem;
}
.video-js .vjs-icon-placeholder {
  width: 100%;
  height: 100%;
  display: block;
}
.concent {
  width: 93%;
  height: auto;
  box-sizing: border-box;
  border: 0.02rem dashed #888888;
  margin-top: 0.3rem;
}
.apply {
  width: 100%;
  height: 1.66rem;
  display: flex;
  align-items: center;
  justify-content: center;
}
.apply .apply_btn {
  width: 5.9rem;
  height: 0.9rem;
  background: #ffb400;
  border-radius: 0.45rem;
  border: none;
  outline: none;
  color: #ffffff;
  font-size: 0.34rem;
  font-weight: bold;
}
.conent {
  width: 100%;
  height: auto;
  font-size: 0.34rem;
}
.brief {
  width: 100%;
  height: auto;
  padding-bottom: 0.2rem;
  border-bottom: 0.2rem solid #eeeeee;
  display: flex;
  flex-direction: column;
  align-items: center;
  p:nth-child(1) {
    width: 93%;
    height: 0.79rem;
    line-height: 0.79rem;
    color: #333333;
    font-size: 0.34rem;
    font-weight: bold;
  }
  p:nth-child(2) {
    width: 93%;
    height: auto;
    color: #666666;
    font-size: 0.28rem;
  }
}
.price {
  width: 100%;
  height: 0.89rem;
  line-height: 0.89rem;
  font-size: 0.34rem;
  color: #000000;
  border-bottom: 0.2rem solid #eeeeee;
  span:nth-child(1) {
    margin-left: 0.29rem;
  }
  .number {
    display: inline-block;
    color: #fc2300;
    margin-left: 0.3rem;
    font-weight: 600;
  }
}
.course {
  width: 100%;
  height: 0.78rem;
  line-height: 0.78rem;
  box-sizing: border-box;
  padding-left: 0.27rem;
  font-size: 0.3rem;
  color: #333333;
}
</style>